var server = require('../../utils/server');
var common = require('../../utils/common');
const app = getApp();
var hideTimer = null;
var countdown = 60;
var settime = function (that) {
  if (countdown == 0) {
    that.setData({
      is_show: true
    })
    countdown = 60;
    return;
  } else {
    that.setData({
      is_show: false,
      last_time: countdown
    })
    countdown--;
  }
};
Page({
  data: {
    showScoreInput: false,
    orderInfo: null,
    storeInfo: [],
    takeInfo:{},
    addressInfo: [],
    remark: "",
    address_id: "",
    selectedAddr: "",
    showAddrStatus: false,
    animationData: [],
    wayanimationData: [],
    timeanimationData: [],
    showPop: false,
    showStorePop: false,
    storeStatusInfo: "",
    location: '',
    delivery_type_list: [],
    deliverType: null,
    isShowTime: false,
    nowTime: '',
    showReceiver: false,
    receiverName: '',
    receiverTel: '',
    newReceiverName: '',
    newReceiverTel: '',
    sourcetype: null,
    showWeightPop: false,
    isPay: true,
    isPayOk: false,
    timeList: [],
    starttime: null,
    endtime: null,
    preTimeList: [],
    prestarttime: null,
    preendtime: null,
    nowDate: '',
    predate: '',
    showOverTimePop: false,
    isFocus: false,
    showDelivery: true,
    isShowCoupon: false,
    couponanimationData: [],
    couponList: [],
    invalidCouponList: [],
    isShowFeeDetail: false,
    preSendTime: '0',
    isCanAddSendOrder: true,
    showPhonePop: false,
    selectgettime: "立即取货",
    selecttimeindex: [0, 0],
    isFromEditAddr: false,
    curtagetSelectAddr: '',
    channelid: "",
    timestap: "",
    memoList: [],
    showMemos: false,
    memoWordsNum: 0,
    isShowTickets: false,
    ticketanimationData: [],
    validTicketList: [],
    invalidTicketList: [],
    isSingleCard: 2,
    curCardTicketTel: '', //校验卡券
    curCardTicketId: '',
    isShowCardVerify: false,
    curCardVerifyCode: '',
    last_time: '',
    is_show: true,
    mesgCode: '',
    isGet: false,
    curCardTicketAmount: '',
    isVerifyPay: false,
    curCouponTab: 0
  },
  onLoad(options) {
    console.log('onload')
    this.setData({
      sourcetype: options.sourcetype
    })
  },
  onUnload() {
    console.log('onunload');
    this.data.isPay = false;
    this.setData({
      isPayOk: false
    })
    clearTimeout(hideTimer);
  },
  onHide() {
    console.log('onhide');
    this.data.isPay = false;
    this.setData({
      isPayOk: false
    })
    clearTimeout(hideTimer);
  },
  hideLoading() {
    wx.hideLoading();
  },
  hideToast() {
    hideTimer = setTimeout(function () {
      wx.hideToast()
    }, 3500)
  },
  onShow: function () {
    console.log('onshow')
    this.setData({
      timestap: Date.parse(new Date())
    })
    wx.getStorage({
      key: 'channelid',
      success: response => {
        this.setData({
          channelid: response.data
        })
        if (response.data == '3000001' || response.data == '10000102' || response.data == '10000147' || response.data == '10000155') {//判断特定渠道进入结算展示优惠券使用gif图
          server.postJSON(common.basePath + 'user/isshow', {
            "type": "djgif",
            "is_checked": 0
          }, res => {
            if (res.data.errno == '0') {
              this.setData({
                showGifTip: res.data.data == 1 ? true : false
              })
            } else {
              common.showErrorToast(res.data.errmsg);
            }
          })
        }
      },
      fail: response => {
        console.log('nochannel')
      }
    })
    this.setData({
      isFromEditAddr: app.globalData.isFromEditAddr
    })
    app.globalData.isGetCartByAdd = true;
    wx.getStorage({
      key: 'orderInfo',
      success: res => {
        var orderData = res.data;
        if (app.globalData.isRefreshAccountList) {
          var checkParam = {
            "address_id": app.globalData.addrId,
            "longitude": app.globalData.longitude,
            "latitude": app.globalData.latitude,
            "store_longitude": orderData.goods.store.longitude,
            "store_latitude": orderData.goods.store.latitude,
            "store_id": orderData.goods.store.store_id,
            "delivery_type": orderData.delivery_default.delivery_type,
            "score_delivery_checked": orderData.goods.score_delivery_checked
          }
          server.postJSON(common.storePath + 'cart/chgaddress', checkParam, res => {
            if (res.data.errno == 0) {
              var data = res.data.data;
              this.dealWithOrderInfo(data)
              wx.setStorage({
                key: 'orderInfo',
                data: data,
                success: resp => {}
              })
            } else {
              common.showToast(res.data.errmsg);
            }
          })
        } else {
          this.dealWithOrderInfo(orderData)
        }
      }
    })
  },
  dealWithOrderInfo(data) {
    var orderData = data;
    this.data.nowtimestamp = (Date.parse(new Date())) / 1000;
    this.data.preendtime = orderData.advance_time.end;
    this.data.prestarttime = orderData.advance_time.start;
    this.setData({
      starttime: orderData.goods.store.take_start_time,
      endtime: orderData.goods.store.take_end_time,
      isCanAddSendOrder: (Date.parse(new Date())) / 1000 >= orderData.goods.store.deliver_start_time ? true : false,
      preSendTime: (Date.parse(new Date())) / 1000 >= orderData.goods.store.deliver_start_time ? this.data.preSendTime : '',
      memoList: orderData.memo_list
    })
    // start 自提时间
    var timemin = parseInt(Math.abs(this.data.endtime - this.data.starttime) / 60),
      timeCounts = timemin / 30,
      sec = 30 * 60 * 1000,
      month = (new Date(this.data.endtime * 1000).getMonth() + 1) >= 10 ? (new Date(this.data.endtime * 1000).getMonth() + 1) : ('0' + (new Date(this.data.endtime * 1000).getMonth() + 1)),
      date = new Date(this.data.endtime * 1000).getDate() >= 10 ? new Date(this.data.endtime * 1000).getDate() : ('0' + new Date(this.data.endtime * 1000).getDate());
    this.data.timeList = this.getDateArray(sec, timeCounts, this.data.endtime, this.data.starttime);
    this.setData({
      nowDate: month + '-' + date
    })
    // end 自提时间
    // start预订单时间
    var pretimemin = parseInt(Math.abs(this.data.preendtime - (this.data.prestarttime + 3600)) / 60),
      pretimeCounts = pretimemin / 15,
      presec = 15 * 60 * 1000,
      pretimeLists = this.getPreDateArray(this.data.preendtime * 1000, presec, pretimeCounts, this.data.preendtime);
    var pred = new Date(this.data.preendtime * 1000);
    var predate = (pred.getHours() >= 10 ? pred.getHours() : '0' + pred.getHours()) + ':' + (pred.getMinutes() >= 10 ? pred.getMinutes() : '0' + pred.getMinutes());
    this.setData({
      predate: predate, //预订单最大时间值
      preTimeList: pretimeLists
    })
    // end预订单时间
    this.getNowTime();
    this.data.deliverTime = orderData.deliver_time[0];
    //获取已选择优惠券数量
    let couponSelectNum = 0;
    if (orderData.goods.coupon_list.length > 0) {
      orderData.goods.coupon_list.forEach(function (item) {
        if (item.is_checked_has == 1) {
          couponSelectNum++;
        }
      })
    }
    var validTicketList = orderData.goods.card_voucher_list.filter((item, index) => {
      return item.error == '';
    })
    var invalidTicketList = orderData.goods.card_voucher_list.filter((item, index) => {
      return item.error != '';
    })
    var curCardTicketInfo = validTicketList.filter((item, index) => {
      return item.is_checked == 1;
    })
    this.setData({
      orderInfo: orderData,
      goodsList: orderData.goods,
      storeInfo: orderData.goods.store,
      takeInfo: orderData.take_store,
      deliverType: orderData.delivery_default.delivery_type,
      defaultType: orderData.delivery_default.delivery_type,
      delivery_type_list: orderData.delivery_type_list,
      couponList: orderData.goods.coupon_list,
      invalidCouponList: orderData.goods.coupon_list_unavailable,
      couponSelectNum: couponSelectNum,
      validTicketList: validTicketList,
      invalidTicketList: invalidTicketList,
      isSingleCard: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].once : 2,
      curCardTicketTel: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].mobile : '',
      curCardTicketAmount: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].balance : '',
      isShowCardVerify: false
    })
    this.data.curCardTicketId = curCardTicketInfo.length > 0 ? curCardTicketInfo[0].bind_id : '';
    if (orderData.delivery_type_list.length == 2) {
      var otherDeliverType = orderData.delivery_type_list.find(function (item, index, arry) {
        return orderData.delivery_default.delivery_type != item.delivery_type
      })
      this.setData({
        otherDeliverType: otherDeliverType.delivery_type
      })
    }
    if (orderData.take_info.mobile != '') {
      this.setData({
        newReceiverTel: orderData.take_info.mobile,
        receiverTel: orderData.take_info.mobile
      })
    }
    if (orderData.take_info.consignee != '') {
      this.setData({
        newReceiverName: orderData.take_info.consignee,
        receiverName: orderData.take_info.consignee,
      })
    }
    if (orderData.score_mobile != '') {
      this.setData({
        scoreCardNum: orderData.score_mobile,
        newScoreCardNum: orderData.score_mobile
      })
    } else if (this.data.scoreCardNum == undefined) {
      app.globalData.isLogin = false;
    }
    if (!app.globalData.isLogin) {
      var that = this;
      setTimeout(function () {
        that.setData({
          showPhonePop: true
        })
      }, 500)
    } else {
      this.setData({
        showPhonePop: false
      })
    }
    if (app.globalData.addrId != null && this.data.deliverType != 1 && this.data.deliverType != 3) {
      var checkParam = {
        "address_id": app.globalData.addrId,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "store_longitude": this.data.storeInfo.longitude,
        "store_latitude": this.data.storeInfo.latitude,
        "store_id": this.data.storeInfo.store_id,
        "delivery_type": this.data.deliverType,
        "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
      }
      if (!this.data.isPay) {
        this.chgAddress(checkParam);
      }
      common.getAddress().then(res => {
        var data = (res.data).filter(function (item) {
          return app.globalData.addrId == item.address_id
        })
        this.setData({
          addressInfo: data[0],
          address_id: data[0].address_id,
        })
      })
    } else if (app.globalData.addrId == null && this.data.sourcetype == null && this.data.deliverType != 1 && this.data.deliverType != 3) {
      this.setData({
        location: app.globalData.location,
        showAddrStatus: true
      })
    } else if (app.globalData.addrId == null && this.data.sourcetype == '0' && this.data.deliverType != 1 && this.data.deliverType != 3) {
      this.setData({
        location: app.globalData.location
      })

    } else if (app.globalData.addrId == null && this.data.deliverType == 1) {
      this.setData({
        location: app.globalData.location
      })
      if ((parseInt(this.data.nowtimestamp)) > this.data.endtime) {
        this.setData({
          showOverTimePop: true
        })
      }
    } else if (app.globalData.addrId != null && this.data.deliverType == 1) {
      this.setData({
        showPop: false,
        isPay: false,
        isPayOk: false
      })
      common.getAddress().then(res => {
        var data = (res.data).filter(function (item) {
          return app.globalData.addrId == item.address_id
        })
        this.setData({
          addressInfo: data[0],
          address_id: data[0].address_id,
        })
      })
      if ((parseInt(this.data.nowtimestamp)) > this.data.endtime) {
        this.setData({
          showOverTimePop: true
        })
      }
    }
  },
  goToChooseAddr() {
    this.setData({
      showAddrStatus: false
    })
    wx.navigateTo({
      url: '../../pages/common/addrListsByCity?fromtype=1&&frompage=dj',
    })
  },
  inputCardNum(e) {
    this.setData({
      newScoreCardNum: e.detail.value
    })
  },
  getRemark(e) {
    this.setData({
      remark: e.detail.value
    })
    if (this.data.remark.length <= 50) {
      this.setData({
        memoWordsNum: this.data.remark.length
      })
    }
  },
  showScoreCardPop() {
    this.setData({
      showScoreInput: true
    })
  },
  hideScoreCard() {
    this.setData({
      showScoreInput: false
    })
  },
  checkScoreCard() {
    server.postJSON(common.basePath + 'member/bindscore/', {
      "mobile": this.data.newScoreCardNum
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          showScoreInput: false,
          scoreCardNum: this.data.newScoreCardNum
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  backCart() {
    this.setData({
      showStorePop: false,
      showWeightPop: false,
      showOverTimePop: false
    })
    wx.navigateBack();
  },
  backCartWithAddr() {
    this.setData({
      showStorePop: false,
      showWeightPop: false,
      showOverTimePop: false
    })
    if (this.data.curtagetSelectAddr != '') {
      app.globalData.skipType = 1;
      app.globalData.addrId = this.data.curtagetSelectAddr.id;
      app.globalData.longitude = this.data.curtagetSelectAddr.lon;
      app.globalData.latitude = this.data.curtagetSelectAddr.la;
      app.globalData.location = this.data.curtagetSelectAddr.addr;
      app.globalData.city = this.data.curtagetSelectAddr.city;
      app.globalData.companyid = "";
      app.globalData.storeType = "";
    }
    app.globalData.isFromEditAddr = false;
    wx.removeStorage({
      key: 'storeId',
      success: function (res) {
        wx.navigateBack();
      },
      fail: res => {
        wx.navigateBack();
      }
    })
  },
  backStore() {
    this.setData({
      showPop: false,
      isPay: false
    })
    wx.navigateTo({
      url: '../../shop/pages/changeStore',
    });
  },
  goToAddr: function (e) {
    app.globalData.companyid = "";
    app.globalData.storeType = "";
    wx.setStorage({
      key: 'companyid',
      data: app.globalData.companyid,
    })
    app.globalData.isFromEditAddr = true;
    wx.navigateTo({
      url: '../../address_manage/pages/editAddr?addrId=' + e.currentTarget.dataset.id + '&&addrType=1'
    })
    this.setData({
      sourcetype: null,
      isPay: false
    })
    this.hideModal()
  },
  pay() {
    app.globalData.orderType = 0;
    var nowtime = new Date(),
      mins = nowtime.getMinutes(),
      hour = nowtime.getHours();
    var now = (hour >= 10 ? hour : '0' + hour) + ':' + (mins >= 10 ? mins : '0' + mins);
    var param = {
      "address_id": this.data.address_id,
      "deliver_time": this.data.deliverTime.code,
      "currency": "63",
      "score_mobile": this.data.scoreCardNum,
      "memo": this.data.remark,
      "store_id": this.data.goodsList.store.store_id,
      "total_goods_amount": this.data.goodsList.total_goods_amount,
      "other_fee": this.data.goodsList.other_fee,
      "discount_fee": this.data.goodsList.discount_fee,
      "total_amount": this.data.goodsList.total_amount,
      "real_amount": this.data.goodsList.real_amount,
      "list": this.data.goodsList.list,
      "distance": this.data.goodsList.distance,
      "weight": this.data.goodsList.weight,
      "distance_fee": this.data.goodsList.distance_fee,
      "weight_fee": this.data.goodsList.weight_fee,
      "time_fee": this.data.goodsList.time_fee,
      "take_time": this.data.nowTime == '立即取货' ? now : this.data.nowTime,
      "delivery_type": this.data.deliverType,
      "consignee": this.data.receiverName,
      "mobile": this.data.receiverTel,
      "coupon_list": this.data.couponList,
      "card_voucher_list": this.data.validTicketList.concat(this.data.invalidTicketList),
      "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked,
      "advance_time": this.data.preSendTime,
      "verify": ''
    }
    if (this.data.deliverType != 1 && this.data.deliverType != 3) {
      if (this.data.address_id == '') {
        this.setData({
          showAddrStatus: true
        })
      } else if (this.data.address_id != '') {
        var checkParam = {
          "address_id": this.data.address_id,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "store_longitude": this.data.storeInfo.longitude,
          "store_latitude": this.data.storeInfo.latitude,
          "store_id": this.data.storeInfo.store_id,
          "delivery_type": this.data.deliverType,
          "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
        }
        server.postJSON(common.storePath + 'cart/chgaddress', checkParam, res => {
          if (res.data.errno == 0) {
            var data = res.data.data;
            if (JSON.stringify(data) == '{}') {
              this.setData({
                showPop: true,
                isPayOk: false
              })
            } else if (JSON.stringify(data) != '{}') {
              this.setData({
                isPayOk: true
              })
              this.goToPay(param)
            }
          } else {
            this.hideLoading();
            common.showToast(res.data.errmsg);
          }
        })
      } else {
        if (this.data.orderInfo.is_advance == 1) {
          if (this.data.preSendTime == '') {
            common.showToast("请选择期望送达时间！");
            this.hideToast();
          } else {
            this.setData({
              isPayOk: true
            })
            this.goToPay(param)
          }
        } else {
          this.setData({
            isPayOk: true
          })
          this.goToPay(param)
        }
      }
    } else if (this.data.deliverType == 1) {
      if (this.data.receiverTel == '') {
        common.showToast("请填写提货人信息！");
        this.hideToast();
      } else if (this.data.receiverName == '') {
        common.showToast("请填写提货人信息！");
        this.hideToast();
      } else if (this.data.nowTime == '') {
        common.showToast("请选择提货时间!");
        var animation1 = wx.createAnimation({
          duration: 300,
          timingFunction: "linear",
          delay: 0
        })
        this.animation = animation1
        this.animation.translateY(500).step()
        this.setData({
          animationData: this.animation.export(),
          isShowTime: true
        })
        setTimeout(function () {
          this.animation.translateY(0).step()
          this.setData({
            animationData: this.animation.export()
          })
        }.bind(this), 200)
      } else {
        this.showStoreExplain()
      }
    } else if (this.data.deliverType == 3) {
      this.goToPay(param)
    }
  },
  goToPay(param) {
    var selectedTicketList = [];
    if (this.data.validTicketList.length > 0) {
      selectedTicketList = this.data.validTicketList.filter((item, index) => {
        return item.is_checked == 1;
      })
    }
    if (this.data.channelid != "") {
      param.channel_id = this.data.channelid;
      if (!app.globalData.isLogin) {
        this.setData({
          showPhonePop: true
        })
      } else {
        if (selectedTicketList.length > 0) {
          //验证电子卡券
          this.setData({
            isShowCardVerify: true,
            isVerifyPay: false
          })
        } else {
          this.addOrder(param);
        }
      }
    } else {
      if (!app.globalData.isLogin) {
        this.setData({
          showPhonePop: true
        })
      } else {
        if (selectedTicketList.length > 0) {
          //验证电子卡券
          this.setData({
            isShowCardVerify: true,
            isVerifyPay: false
          })
        } else {
          this.addOrder(param);
        }
      }
    }
  },
  addOrder(param) {
    if (app.globalData.accountRandom == '') {
      app.globalData.accountRandom = Math.random();
      server.postJSON(common.storePath + 'order/add/', param, res => {
        app.globalData.accountRandom = '';
        if (res.data.errno == "0") {
          app.globalData.accountRandom = '';
          app.globalData.refreshTag = true;
          app.globalData.isAccount = true;
          this.setData({
            isPayOk: false,
            isVerifyPay: false
          })
          var orderId = res.data.data.order_id,
            realAmount = res.data.data.real_amount;
          this.data.orderid = res.data.data.order_id;
          var recommendIds = [];
          param.list.forEach((item, index) => {
            recommendIds.push(item.goods_id)
          })
          wx.setStorage({
            key: 'orderId',
            data: orderId,
            success: ret => {
              if (realAmount > 0) {
                wx.hideLoading();
                if (app.globalData.sdkversion >= 282 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
                  server.postJSON(common.basePath + 'miniprogram/getnewtemplateid', {
                    "type": "pay"
                  }, res => {
                    wx.hideLoading();
                    if (res.data.errno == '0') {
                      var ids = [];
                      (res.data.data).forEach((item, index) => {
                        ids.push(item)
                      })
                      var that = this;
                      wx.requestSubscribeMessage({
                        tmplIds: ids,
                        success(res) {
                          that.payByWx(orderId);
                        },
                        fail(res) {
                          that.payByWx(orderId);
                        }
                      })
                    } else {
                      common.showErrorToast(res.data.errmsg);
                    }
                  })
                } else {
                  var that = this;
                  wx.showModal({
                    title: '微信版本升级提示',
                    content: '当前微信版本过低，无法获得订阅消息通知，请升级最新微信版本。',
                    showCancel: false,
                    confirmText: "我知道了",
                    success(res) {
                      that.payByWx(orderId);
                    }
                  })
                }
              } else {
                wx.hideLoading();
                this.sendWxTemplate();
              }
              wx.setStorage({
                key: 'recommendIds',
                data: recommendIds,
              })
            }
          })
        } else {
          if (res.data.errmsg == undefined) {
            common.showToast("数据出错啦T_T，请稍候再试 [-3]");
          } else if (res.data.errno == "1000000") {
            this.setData({
              showStorePop: true,
              storeStatusInfo: res.data.data.status_tip,
              isShowCardVerify: false
            })
          } else {
            common.showToast(res.data.errmsg);
          }
          this.setData({
            isPayOk: false,
            isVerifyPay: false
          })
          this.hideToast();
        }
      })
    } else {
      app.globalData.accountRandom = '';
      common.showErrorToast("订单已生成，请从订单列表查看");
      setTimeout(() => {
        wx.switchTab({
          url: '../../pages/order/orderIndex',
        })
      }, 2000);
    }
  },
  showModal() {
    wx.navigateTo({
      url: '../../pages/common/addrListsByCity?fromtype=1&&frompage=dj',
    })
  },
  //参数变更重新获取结算信息
  chgAddress(checkParam) {
    server.postJSON(common.storePath + 'cart/chgaddress', checkParam, res => {
      if (res.data.errno == 0) {
        var data = res.data.data;
        if (JSON.stringify(data) == '{}') {
          this.setData({
            showPop: true,
            isPayOk: false
          })
          if ((parseInt(this.data.nowtimestamp) + 15 * 60) > this.data.endtime) {
            this.setData({
              showDelivery: false
            })
          } else {
            this.setData({
              showDelivery: true
            })
          }
          wx.getStorage({
            key: 'orderInfo',
            success: resp => {
              this.data.validTicketList = [];
              this.data.invalidTicketList = [];
              var validTicketList = resp.data.goods.card_voucher_list.filter((item, index) => {
                return item.error == '';
              })
              var invalidTicketList = resp.data.goods.card_voucher_list.filter((item, index) => {
                return item.error != '';
              })
              this.data.curCardTicketId = '';
              this.setData({
                validTicketList: validTicketList,
                invalidTicketList: invalidTicketList,
                curCardTicketTel: '',
                curCardTicketAmount: '',
                isShowCardVerify: false
              })
            },
          })
        } else if (JSON.stringify(data) != '{}') {
          if (this.data.deliverType == 0 && data.goods.weight > 15) {
            this.setData({
              showWeightPop: true
            })
          }
          let couponSelectNum = 0;
          if (data.goods.coupon_list.length > 0) {
            data.goods.coupon_list.forEach(function (item) {
              if (item.is_checked_has == 1) {
                couponSelectNum++;
              }
            })
          }
          if (checkParam.address_id != null) {
            app.globalData.longitude = data.address.longitude;
            app.globalData.latitude = data.address.latitude;
            app.globalData.location = data.address.address;
          }
          this.data.deliverTime = data.deliver_time[0];
          this.data.validTicketList = [];
          this.data.invalidTicketList = [];
          var validTicketList = data.goods.card_voucher_list.filter((item, index) => {
            return item.error == '';
          })
          var curCardTicketInfo = validTicketList.filter((item, index) => {
            return item.is_checked == 1;
          })
          var invalidTicketList = data.goods.card_voucher_list.filter((item, index) => {
            return item.error != '';
          })
          this.setData({
            orderInfo: data,
            goodsList: data.goods,
            storeInfo: data.goods.store,
            takeInfo: data.take_store,
            deliverType: data.delivery_default.delivery_type,
            delivery_type_list: data.delivery_type_list,
            couponList: data.goods.coupon_list,
            invalidCouponList: data.goods.coupon_list_unavailable,
            couponSelectNum: couponSelectNum,
            validTicketList: validTicketList,
            invalidTicketList: invalidTicketList,
            showPop: false,
            isPayOk: false,
            isCanAddSendOrder: (Date.parse(new Date())) / 1000 >= data.goods.store.deliver_start_time ? true : false,
            isSingleCard: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].once : 2,
            curCardTicketTel: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].mobile : '',
            curCardTicketAmount: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].balance : ''
          })
          this.data.curCardTicketId = curCardTicketInfo.length > 0 ? curCardTicketInfo[0].bind_id : '';
          var nowtime = new Date(),
            premins = nowtime.getMinutes() + 60,
            prehours = premins >= 45 ? nowtime.getHours() + 1 : nowtime.getHours(),
            prenowmin = premins >= 60 ? premins - 60 : premins;
          var prenow = (prehours >= 10 ? prehours : '0' + prehours) + ':' + (prenowmin >= 10 ? prenowmin : '0' + prenowmin);
          var prenewnow = this.data.preTimeList.find(function (value, index, arr) {
            return value > prenow;
          })
          this.setData({
            prenewnow: prenewnow == undefined ? '' : prenewnow
          })
          if (prenewnow != undefined && this.data.preSendTime >= prenewnow) {
            this.setData({
              preSendTime: (Date.parse(new Date())) / 1000 >= data.goods.store.deliver_start_time ? this.data.preSendTime : ''
            })
          } else {
            this.setData({
              preSendTime: (Date.parse(new Date())) / 1000 >= data.goods.store.deliver_start_time ? '0' : ''
            })
          }
          wx.setStorage({
            key: 'orderInfo',
            data: data,
            success: res => {

            }
          })
        }
        this.hideLoading();
      } else {
        this.hideLoading();
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  cancelDelivery() {
    this.setData({
      showPop: false
    })
  },
  // 隐藏底部地址弹框
  hideModal() {
    var animation2 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation2;
    this.animation.translateY(300).step();
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        animationData: this.animation.export(),
        showAddrStatus: false
      })
    }.bind(this), 200)
  },
  //单选框切换配送方式
  selectSendWay(e) {
    var deliverType = e.currentTarget.dataset.value;
    this.setData({
      isFocus: false
    })
    this.changeSendWay(deliverType)
  },

  //切换配送方式逻辑
  changeSendWay(deliverType) {
    this.data.orderInfo.delivery_default.delivery_type = deliverType;
    wx.setStorage({
      key: 'orderInfo',
      data: this.data.orderInfo,
    })
    this.data.isPay = false;
    this.setData({
      deliverType: deliverType,
      orderInfo: this.data.orderInfo,
      isPayOk: false,
      curCouponTab: 0
    })
    if (this.data.delivery_type_list.length == 2) {
      var otherDeliverType = this.data.delivery_type_list.find(function (item, index, arry) {
        return deliverType != item.delivery_type
      })
      this.setData({
        otherDeliverType: otherDeliverType.delivery_type
      })
    }
    app.globalData.deliverType = deliverType;
    var checkParam = {
      "address_id": app.globalData.addrId,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude,
      "store_longitude": this.data.storeInfo.longitude,
      "store_latitude": this.data.storeInfo.latitude,
      "store_id": this.data.storeInfo.store_id,
      "delivery_type": this.data.deliverType,
      "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
    }
    if (deliverType == 0 && this.data.goodsList.weight > 15) {
      this.setData({
        showWeightPop: true
      })
    } else {
      if (app.globalData.addrId == null && this.data.deliverType != 1 && this.data.deliverType != 3) {
        this.setData({
          location: app.globalData.location,
          showAddrStatus: true
        })
      } else if (app.globalData.addrId != null && this.data.deliverType != 1 && this.data.deliverType != 3) {
        this.setData({
          isPayOk: true
        })
        this.chgAddress(checkParam);
      } else if (deliverType == 1) {
        this.setData({
          isPayOk: true
        })
        this.chgAddress(checkParam);
        if ((parseInt(this.data.nowtimestamp)) > this.data.endtime) {
          this.setData({
            showOverTimePop: true
          })
        } else {
          var nowtime = new Date(),
            mins = nowtime.getMinutes(),
            nowhours = mins >= 45 ? nowtime.getHours() + 1 : nowtime.getHours(),
            nowmin = mins + 15 >= 60 ? 60 - mins : mins + 15;
          var now = (nowhours >= 10 ? nowhours : '0' + nowhours) + ':' + (nowmin >= 10 ? nowmin : '0' + nowmin);
          var newnow = this.data.timeList.find(function (value, index, arr) {
            return value > now;
          })
          this.setData({
            nowTime: newnow == undefined ? '' : this.data.nowTime,
            now: newnow == undefined ? '' : newnow
          })

        }

      }
    }
  },
  showGetGoodsTime() {
    var animation1 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
      isShowTime: true
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        animationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  //选择自提时间
  selectGetTime() {
    this.setData({
      nowTime: this.data.selectgettime,
      selecttimeindex: this.data.selecttimeindex
    })
    this.hideTimeModal()
  },
  bindTimeChange(e) {
    var index = e.detail.value[1]
    this.data.selectgettime = index == 0 ? '立即取货' : this.data.timeList[index - 1];
    this.data.selecttimeindex = e.detail.value;
  },
  hideTimeModal() {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        wayanimationData: animation.export(),
        isShowTime: false,
        isShowPreTime: false
      })
    }.bind(this), 200)
  },
  showReceiverPop() {
    this.setData({
      showReceiver: true
    })
  },
  hideReceiverPop() {
    this.setData({
      showReceiver: false
    })
  },
  inputUserName(e) {
    this.setData({
      newReceiverName: e.detail.value
    })
  },
  inputTel(e) {
    this.setData({
      newReceiverTel: e.detail.value
    })
  },
  saveReceiver() {
    if (this.data.newReceiverName == '' || this.data.newReceiverTel == '') {
      common.showToast('请填写提货人信息！');
      this.hideToast();
    } else if (this.data.newReceiverTel.length != 11) {
      common.showToast('请填写正确的手机号码！');
      this.hideToast();
    } else {
      this.setData({
        showReceiver: false,
        receiverName: this.data.newReceiverName,
        receiverTel: this.data.newReceiverTel,
      })
    }
  },
  getNowTime() {
    var nowtime = new Date(),
      mins = nowtime.getMinutes(),
      premins = nowtime.getMinutes() + 60,
      nowhours = mins >= 45 ? nowtime.getHours() + 1 : nowtime.getHours(),
      prehours = premins >= 45 ? nowtime.getHours() + 1 : nowtime.getHours(),
      nowmin = mins + 15 >= 60 ? 60 - mins : mins + 15,
      prenowmin = premins >= 60 ? premins - 60 : premins;
    var now = (nowhours >= 10 ? nowhours : '0' + nowhours) + ':' + (nowmin >= 10 ? nowmin : '0' + nowmin);
    var prenow = (prehours >= 10 ? prehours : '0' + prehours) + ':' + (prenowmin >= 10 ? prenowmin : '0' + prenowmin);

    var newnow = this.data.timeList.find(function (value, index, arr) {
      return value > now;
    })
    this.data.timeList = this.data.timeList.filter((item, index) => {
      return item >= now
    })
    this.setData({
      timeList: this.data.timeList
    })
    var prenewnow = this.data.preTimeList.find(function (value, index, arr) {
      return value > prenow;
    })
    if (newnow != undefined) {
      if (this.data.nowTime != '' && this.data.nowTime != '立即取货') {
        this.setData({
          nowTime: newnow
        })
      } else {
        this.setData({
          nowTime: '立即取货'
        })
      }
    } else {
      this.setData({
        nowTime: ''
      })
    }
    this.setData({
      now: newnow == undefined ? '' : newnow,
      prenewnow: prenewnow == undefined ? '' : prenewnow
    })
  },
  getDateArray(splitTime, count, endtime, starttime) {
    var starttime = starttime * 1000,
      endtime = endtime * 1000;

    function formatTime(time) { //时间为个位数则补零
      return time < 10 ? '0' + time : time;
    }
    var list = [];
    for (let j = 0; j < count; j++) {
      if (starttime + splitTime <= endtime) {
        //将各子区间日期按半小时递增转换为时间并存入list数组
        let ss = new Date(starttime + splitTime * j),
          ee = new Date(starttime + splitTime * (j + 1));
        list.push([formatTime(ss.getHours()) + ':' + formatTime(ss.getMinutes()), formatTime(ee.getHours()) + ':' + formatTime(ee.getMinutes())]);
      }
    }
    list = list.map(item => {
      return item.join('-');
    })
    return list;
  },
  getPreDateArray(endDate, splitTime, count, endtime) {
    var dateArray = [];
    while (count-- > 0) {
      var d = new Date(endtime * 1000 - count * splitTime);
      if (count * splitTime >= 0) {
        var date = (d.getHours() >= 10 ? d.getHours() : '0' + d.getHours()) + ':' + (d.getMinutes() >= 10 ? d.getMinutes() : '0' + d.getMinutes());
        dateArray.push(date);
      }
    }
    return dateArray;
  },
  showExplain() {
    this.setData({
      isShowExplain: true
    })
  },
  hideExplain() {
    this.setData({
      isShowExplain: false
    })
  },
  focusRemark() {
    this.setData({
      isFocus: true
    })
  },
  confirmTextarea() {
    this.setData({
      isFocus: false
    })
  },
  //选择默认备注
  selectMemo(e) {
    var remark = this.data.remark + e.currentTarget.dataset.memo + ';';
    if (remark.length <= 50) {
      this.setData({
        remark: remark,
        memoWordsNum: remark.length
      })
    } else if (remark.length > 50) {
      this.setData({
        remark: remark.substring(0, 50),
        memoWordsNum: 50
      })
    }
  },
  //切换到蜂鸟配送
  changeToDelivery() {
    this.changeSendWay(this.data.otherDeliverType);
    this.setData({
      showOverTimePop: false
    })

  },
  //切换到到店自提
  changeToSelfLift() {
    var deliverType = 1;
    this.data.orderInfo.delivery_default.delivery_type = deliverType;
    this.setData({
      deliverType: deliverType,
      orderInfo: this.data.orderInfo,
      showPop: false,
      showWeightPop: false,
      isPayOk: false
    })
    var checkParam = {
      "address_id": app.globalData.addrId,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude,
      "store_longitude": this.data.storeInfo.longitude,
      "store_latitude": this.data.storeInfo.latitude,
      "store_id": this.data.storeInfo.store_id,
      "delivery_type": 1,
      "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
    }
    this.chgAddress(checkParam);
    app.globalData.deliverType = deliverType;
    if ((parseInt(this.data.nowtimestamp)) > this.data.endtime) {
      this.setData({
        showOverTimePop: true
      })
    } else {
      var nowtime = new Date(),
        mins = nowtime.getMinutes(),
        nowhours = mins >= 45 ? nowtime.getHours() + 1 : nowtime.getHours(),
        nowmin = mins + 15 >= 60 ? 60 - mins : mins + 15;
      var now = (nowhours >= 10 ? nowhours : '0' + nowhours) + ':' + (nowmin >= 10 ? nowmin : '0' + nowmin);
      var newnow = this.data.timeList.find(function (value, index, arr) {
        return value > now;
      })
      this.setData({
        nowTime: newnow == undefined ? '' : this.data.nowTime,
        now: newnow == undefined ? '' : newnow
      })
    }
  },
  //切换到门店购
  changeToStoreBuy() {
    var deliverType = 3;
    this.data.orderInfo.delivery_default.delivery_type = deliverType;
    this.setData({
      deliverType: deliverType,
      orderInfo: this.data.orderInfo,
      showPop: false,
      isPayOk: false,
      showWeightPop: false
    })
    app.globalData.deliverType = deliverType;
    wx.setStorage({
      key: 'orderInfo',
      data: this.data.orderInfo,
      success: res => {}
    })
  },
  showCoupons() {
    this.setData({
      isPayOk: true
    })
    // 显示遮罩层
    var animation1 = wx.createAnimation({
      duration: 300,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(500).step()
    this.setData({
      couponanimationData: this.animation.export(),
      isShowCoupon: !this.data.isShowCoupon
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        couponanimationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  hideCouponList() {
    var animation1 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(300).step()
    this.setData({
      couponanimationData: this.animation.export(),
      isShowCoupon: !this.data.isShowCoupon,
      curCouponTab: 0
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        couponanimationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  cancelUseCoupons() {
    wx.getStorage({
      key: 'orderInfo',
      success: res => {
        this.setData({
          couponList: res.data.goods.coupon_list,
          isPayOk: false
        })
      },
    })

    this.hideCouponList();
  },
  selectCoupon(e) {
    var vouchertype = e.currentTarget.dataset.vouchertype,
      curVoucherId = e.currentTarget.dataset.voucherid;
    if (vouchertype == 4) {
      this.data.couponList.forEach(function (item) {
        if (item.goods_type == vouchertype) {
          item.is_checked = 1;
          if (item.coupon_id == curVoucherId) {
            item.is_checked_has = item.is_checked_has == 1 ? 0 : 1
          }
        } else {
          item.is_checked_has = 0;
          item.is_checked = 0;
        }
      })
      this.setData({
        couponList: this.data.couponList
      })
    } else {
      this.data.couponList.forEach(function (item) {
        if (item.goods_type == vouchertype) {
          if (item.coupon_id != curVoucherId) {
            item.is_checked = 0;
            item.is_checked_has = 0;
          }
          if (item.coupon_id == curVoucherId) {
            item.is_checked = 1;
            item.is_checked_has = item.is_checked_has == 1 ? 0 : 1;
          }
        } else {
          item.is_checked_has = 0;
          item.is_checked = 0;
        }
      })
      this.setData({
        couponList: this.data.couponList
      })
    }

    let couponSelectNum = 0;
    this.data.couponList.forEach(function (item) {
      if (item.is_checked_has == 1) {
        couponSelectNum++;
      }
    })
    if (couponSelectNum == 0) {
      this.data.couponList.forEach(function (item) {
        item.is_checked = 1;
      })
      this.setData({
        couponList: this.data.couponList
      })
    }
    this.data.couponSelectNum = couponSelectNum;
  },
  confirmUseCoupon() {
    this.hideCouponList();
    if (this.data.couponList.length > 0) {
      this.setData({
        couponSelectNum: this.data.couponSelectNum
      })
      var checkParam = {
        "address_id": app.globalData.addrId,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "store_longitude": this.data.storeInfo.longitude,
        "store_latitude": this.data.storeInfo.latitude,
        "store_id": this.data.storeInfo.store_id,
        "delivery_type": this.data.deliverType,
        "coupon_list": this.data.couponList,
        "coupon_list_unavailable": this.data.invalidCouponList,
        "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
      }
      this.chgAddress(checkParam);
    } else {
      this.setData({
        isPayOk: false
      })
    }
  },
  showStoreExplain() {
    var nowtime = new Date(),
      mins = nowtime.getMinutes(),
      hour = nowtime.getHours();
    var now = (hour >= 10 ? hour : '0' + hour) + ':' + (mins >= 10 ? mins : '0' + mins);
    var param = {
      "address_id": this.data.address_id,
      "deliver_time": this.data.deliverTime.code,
      "currency": "63",
      "score_mobile": this.data.scoreCardNum,
      "memo": this.data.remark,
      "store_id": this.data.goodsList.store.store_id,
      "total_goods_amount": this.data.goodsList.total_goods_amount,
      "other_fee": this.data.goodsList.other_fee,
      "discount_fee": this.data.goodsList.discount_fee,
      "total_amount": this.data.goodsList.total_amount,
      "real_amount": this.data.goodsList.real_amount,
      "list": this.data.goodsList.list,
      "distance": this.data.goodsList.distance,
      "weight": this.data.goodsList.weight,
      "distance_fee": this.data.goodsList.distance_fee,
      "weight_fee": this.data.goodsList.weight_fee,
      "time_fee": this.data.goodsList.time_fee,
      "take_time": this.data.nowTime == '立即取货' ? now : this.data.nowTime,
      "delivery_type": this.data.deliverType,
      "consignee": this.data.receiverName,
      "mobile": this.data.receiverTel,
      "coupon_list": this.data.couponList,
      "coupon_list_unavailable": this.data.invalidCouponList,
      "card_voucher_list": this.data.validTicketList.concat(this.data.invalidTicketList),
      "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked,
      "advance_time": this.data.preSendTime
    }
    this.goToPay(param)
  },
  changeScoreDelivery(e) {
    this.setData({
      isPayOk: true
    })
    var checkParam = {
      "address_id": app.globalData.addrId,
      "longitude": app.globalData.longitude,
      "latitude": app.globalData.latitude,
      "store_longitude": this.data.storeInfo.longitude,
      "store_latitude": this.data.storeInfo.latitude,
      "store_id": this.data.storeInfo.store_id,
      "delivery_type": this.data.deliverType,
      "coupon_list": this.data.couponList,
      "coupon_list_unavailable": this.data.invalidCouponList,
      "score_delivery_checked": e.detail.value ? 1 : 0
    }
    common.showLoading("结算中...");
    this.chgAddress(checkParam);
  },
  showFeeDetail() {
    this.setData({
      isShowFeeDetail: !this.data.isShowFeeDetail
    })
  },
  showPreTimeList() {
    var animation1 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
      isShowPreTime: true
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        animationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  selectPreSendTime(e) {
    this.setData({
      preSendTime: e.currentTarget.dataset.time
    })
    this.hideTimeModal();
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false,
      isPayOk: false
    })
  },
  // 电子卡券
  showTickets() {
    this.setData({
      isPayOk: true
    })
    var animation1 = wx.createAnimation({
      duration: 450,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(600).step()
    this.setData({
      ticketanimationData: this.animation.export(),
      isShowTickets: !this.data.isShowTickets
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        ticketanimationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  hideTicketList() {
    var animation1 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation1
    this.animation.translateY(200).step()
    this.setData({
      ticketanimationData: this.animation.export(),
      isShowTickets: !this.data.isShowTickets
    })
    setTimeout(function () {
      this.animation.translateY(0).step()
      this.setData({
        ticketanimationData: this.animation.export()
      })
    }.bind(this), 200)
  },
  cancelUseTickets() {
    wx.getStorage({
      key: 'orderInfo',
      success: res => {
        this.data.validTicketList = [];
        this.data.invalidTicketList = [];
        var validTicketList = res.data.goods.card_voucher_list.filter((item, index) => {
          return item.error == '';
        })
        var curCardTicketInfo = validTicketList.filter((item, index) => {
          return item.is_checked == 1;
        })
        var invalidTicketList = res.data.goods.card_voucher_list.filter((item, index) => {
          return item.error != '';
        })
        this.setData({
          validTicketList: validTicketList,
          invalidTicketList: invalidTicketList,
          isSingleCard: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].once : 2,
          isPayOk: false,
          curCardTicketTel: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].mobile : '',
          curCardTicketAmount: curCardTicketInfo.length > 0 ? curCardTicketInfo[0].balance : ''
        })
        this.data.curCardTicketId = curCardTicketInfo.length > 0 ? curCardTicketInfo[0].bind_id : '';
      },
    })
    this.hideTicketList();
  },
  selectTicket(e) {
    var vouchertype = e.currentTarget.dataset.vouchertype,
      curVoucherId = e.currentTarget.dataset.voucherid,
      curVoucherError = e.currentTarget.dataset.verror;
    if (curVoucherError == '') {
      this.data.validTicketList.forEach(function (item) {
        if (item.bind_id == curVoucherId) {
          item.is_checked = item.is_checked == 1 ? 0 : 1;
        } else {
          item.is_checked = 0;
        }
      })
      this.setData({
        validTicketList: this.data.validTicketList
      })
    }
  },
  confirmUseTickets() {
    this.hideTicketList();
    if (this.data.validTicketList.length > 0) {
      var checkParam = {
        "address_id": app.globalData.addrId,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "store_longitude": this.data.storeInfo.longitude,
        "store_latitude": this.data.storeInfo.latitude,
        "store_id": this.data.storeInfo.store_id,
        "delivery_type": this.data.deliverType,
        "card_voucher_list": this.data.validTicketList.concat(this.data.invalidTicketList),
        "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked
      }
      this.chgAddress(checkParam);
    } else {
      this.setData({
        isPayOk: false
      })
    }
  },
  closeGifPop() {
    server.postJSON(common.basePath + 'user/isshow', {
      "type": "djgif",
      "is_checked": 1
    }, res => {
      if (res.data.errno == '0') {
        this.setData({
          showGifTip: false
        })
      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
    wx.removeStorage({
      key: 'channelid',
      success: function (res) {
      },
    })
  },

  payByWx(orderid) {
    app.globalData.isBindYcCard = false;
    this.setData({
      isPayOk: true
    })
    var param = {
      "currency": '63',
      "order_id": orderid
    }
    common.pay(param).then(res => {
      if (res.errno == "0") {
        var outtradeno = res.data.out_trade_no;
        app.actionReport('REQUEST_PAYMENT', {
          // 商户订单号(必须)
          out_trade_no: outtradeno,
          take_type: (this.data.deliverType != 1 && this.data.deliverType != 3) ? 'DELIVERY' : 'STORE',
        })
        //发起支付
        var payParam = res.data;
        var that = this;

        payParam.complete = function (ret3) {
          common.showLoading("支付中...");
          //支付成功
          var isSuc = ret3.errMsg == 'requestPayment:ok';
          wx.reportAnalytics('pay_status', {
            paystatus: isSuc,
            orderid: orderid
          });
          if (isSuc) {
            common.hideLoading();
            wx.reportAnalytics('pay_success', {
              paystatus: isSuc,
              orderid: orderid
            });
            server.postJSON(common.storePath + 'order/payrespond/', {
              'out_trade_no': outtradeno
            }, resp => {
              that.setData({
                isPayOk: true
              })
              wx.removeStorage({
                key: 'channelid',
                success: function (res) {
                },
              })
              wx.redirectTo({
                url: '../../pay/pages/paySuccess?orderId=' + orderid
              })
            })
          } else {
            common.hideLoading();
            that.setData({
              isPayOk: true
            })
            wx.reportAnalytics('pay_fail', {
              paystatus: isSuc,
              orderid: orderid
            });
            wx.showToast({
              title: '支付失败',
              duration: 2000,
              complete: function () {
                wx.redirectTo({
                  url: '../../pay/pages/payFail?way=0&&orderId=' + orderid + '&&errmesg=微信支付失败'
                })
              }
            });
          }
        }
        wx.requestPayment(payParam);
      } else {
        if (res.errmsg == undefined) {
          common.showToast("数据出错啦T_T，请稍候再试 [-3]");
          time = setTimeout(function () {
            wx.hideToast()
          }, 3500)
        } else if (res.errno == "1000000") {
          this.setData({
            showStorePop: true,
            storeStatusInfo: res.data.status_tip,
            isShowCardVerify: false
          })
        } else {
          common.showErrorToast(res.errmsg);
        }
      }
    })
  },
  sendWxTemplate() {
    if (app.globalData.sdkversion >= 282 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      server.postJSON(common.basePath + 'miniprogram/getnewtemplateid', {
        "type": "pay"
      }, res => {
        if (res.data.errno == '0') {
          var ids = [];
          (res.data.data).forEach((item, index) => {
            ids.push(item)
          })
          var that = this;
          wx.requestSubscribeMessage({
            tmplIds: ids,
            success(res) {
              console.log(res, '订阅成功')
              wx.redirectTo({
                url: '../../pay/pages/paySuccess?orderId=' + that.data.orderid
              })
            },
            fail(res) {
              wx.redirectTo({
                url: '../../pay/pages/paySuccess?orderId=' + that.data.orderid
              })
            }
          })
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    } else {
      var that = this;
      wx.showModal({
        title: '微信版本升级提示',
        content: '当前微信版本过低，无法获得订阅消息通知，请升级最新微信版本。',
        showCancel: false,
        confirmText: "我知道了",
        success(res) {
          wx.redirectTo({
            url: '../../pay/pages/paySuccess?orderId=' + that.data.orderid
          })
        }
      })
    }
  },
  toggleAllMemos() {
    this.setData({
      showMemos: !this.data.showMemos
    })
  },
  goToBindCard() {
    wx.navigateTo({
      url: '../../pages/memberCard/bindYcCard?type=account',
    })
  },
  getCardVerifyCode() {
    server.postJSON(common.basePath + 'card/verifybind/', {
      "mobile": this.data.curCardTicketTel,
      "type": 5,
      "real_amount": this.data.curCardTicketAmount
    }, res => {
      if (res.data.errno == "0") {
        this.setData({
          is_show: false,
          isGet: false
        })
        settime(this);
      } else {
        this.setData({
          is_show: true,
          isGet: false
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  inputCardVerifyCode(e) {
    this.setData({
      curCardVerifyCode: e.detail.value
    })
  },
  hideCardVerify() {
    this.setData({
      isShowCardVerify: false,
      isPayOk: false,
      isVerifyPay: false
    })
  },
  checkCardTicket() {
    if (this.data.curCardVerifyCode != '') {
      this.setData({
        isVerifyPay: true
      })
      var nowtime = new Date(),
        mins = nowtime.getMinutes(),
        hour = nowtime.getHours();
      var now = (hour >= 10 ? hour : '0' + hour) + ':' + (mins >= 10 ? mins : '0' + mins);
      var param = {
        "address_id": this.data.address_id,
        "deliver_time": this.data.deliverTime.code,
        "currency": "63",
        "score_mobile": this.data.scoreCardNum,
        "memo": this.data.remark,
        "store_id": this.data.goodsList.store.store_id,
        "total_goods_amount": this.data.goodsList.total_goods_amount,
        "other_fee": this.data.goodsList.other_fee,
        "discount_fee": this.data.goodsList.discount_fee,
        "total_amount": this.data.goodsList.total_amount,
        "real_amount": this.data.goodsList.real_amount,
        "list": this.data.goodsList.list,
        "distance": this.data.goodsList.distance,
        "weight": this.data.goodsList.weight,
        "distance_fee": this.data.goodsList.distance_fee,
        "weight_fee": this.data.goodsList.weight_fee,
        "time_fee": this.data.goodsList.time_fee,
        "take_time": this.data.nowTime == '立即取货' ? now : this.data.nowTime,
        "delivery_type": this.data.deliverType,
        "consignee": this.data.receiverName,
        "mobile": this.data.receiverTel,
        "coupon_list": this.data.couponList,
        "coupon_list_unavailable": this.data.invalidCouponList,
        "card_voucher_list": this.data.validTicketList.concat(this.data.invalidTicketList),
        "score_delivery_checked": this.data.orderInfo.goods.score_delivery_checked,
        "advance_time": this.data.preSendTime,
        "verify": this.data.curCardVerifyCode, //校验卡券验证码
        "channel_id": this.data.channelid == '' ? '' : this.data.channelid
      }
      wx.showLoading({
        title: '',
      })
      this.addOrder(param)
    } else {
      common.showErrorToast('请先输入验证码')
    }
  },
  changeCouponType(e) {
    this.setData({
      curCouponTab: e.currentTarget.dataset.id
    })
  }
})